from flask import request
from flask import session, jsonify

from info import constants
from info.models import User, Category, News
from info.utils.response_code import RET
from . import index_blue
from flask import render_template, current_app


@index_blue.route('/news_list')
def news_list():
    # 一. 获取参数
    # cid没有1这个分类, 如果是1,代表查询所有分类的最新数据
    cid = request.args.get('cid', 1)
    page = request.args.get('page', 1)
    per_page = request.args.get('per_page', 10)

    # 二.校验参数
    try:
        cid = int(cid)
        page = int(page)
        per_page = int(per_page)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg='参数有误')

    # 三. 逻辑处理
    filters = [News.status == 0]

    if cid != 1:
        filters.append(News.category_id == cid)

    try:
        paginates = News.query.filter(*filters).order_by(News.create_time.desc()).paginate(page, per_page, False)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='数据库错误')

    news_models = paginates.items

    # 获取分页的总页码
    total_page = paginates.pages

    # 获取当前页码
    current_page = paginates.page

    news_list = []
    for news in news_models:
        news_list.append(news.to_basic_dict())

    data = {
        'news_list': news_list,
        'total_page': total_page ,
        'current_page': current_page
    }

    return jsonify(errno=RET.OK, errmsg="成功", data=data)


@index_blue.route('/')
def index():
    # 读取session数据
    user_id = session.get('user_id', None)

    # 查询user_id三,获取用户数据
    user = None
    if user_id:
        try:
            user =User.query.get(user_id)
        except Exception as e:
            current_app.logger.error(e)

    categorys = None
    try:
        categorys = Category.query.all()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='数据库错误')

    category_list = []
    for category in categorys if categorys else []:
        category_list.append(category.to_dict())

    news_model = None
    try:
        news_model = News.query.order_by(News.clicks.desc()).limit(constants.CLICK_RANK_MAX_NEWS)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='数据库错误')
    click_news_list = []
    for news in news_model if news_model else []:
        click_news_list.append(news.to_basic_dict())

    # 拼接返回数据字典
    data = {
        # 为了方便返回所需要的数据, 我们开发中一般会自定义to_dict函数
        # user有值, 就返回前面的数据, 没有值, 就返回None --> 模板就解析不出来数据
        # 模型转字典
        'user': user.to_index_dict() if user else None,
        'categorys_list': category_list,
        'click_list': click_news_list
    }

    return render_template('news/index.html', data=data)


@index_blue.route('/favicon.ico')
def favicon():
    return current_app.send_static_file('news/favicon.ico')